package com.imufe.chemicalenterprisedangerwarning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imufe.chemicalenterprisedangerwarning.entity.po.CheckUnitPO;
import com.imufe.chemicalenterprisedangerwarning.entity.po.ChemicalPO;
import com.imufe.chemicalenterprisedangerwarning.entity.po.UnitItemPO;
import com.imufe.chemicalenterprisedangerwarning.entity.query.UnitItemQuery;
import com.imufe.chemicalenterprisedangerwarning.entity.vo.CheckItemVO;
import com.imufe.chemicalenterprisedangerwarning.entity.vo.UnitItemDetailedVO;
import com.imufe.chemicalenterprisedangerwarning.exception.ValidationException;
import com.imufe.chemicalenterprisedangerwarning.mapper.CheckItemMapper;
import com.imufe.chemicalenterprisedangerwarning.mapper.UnitItemMapper;
import com.imufe.chemicalenterprisedangerwarning.service.CheckItemService;
import com.imufe.chemicalenterprisedangerwarning.service.UnitItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imufe.chemicalenterprisedangerwarning.util.BeanUtils;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 模块条目表 服务实现类
 * </p>
 *
 * @author BaiBan
 * @since 2022-10-06
 */
@Log4j2
@Service
public class UnitItemServiceImpl extends ServiceImpl<UnitItemMapper, UnitItemPO> implements UnitItemService {

    @Autowired
    UnitItemMapper mapper;

    @Autowired
    CheckItemService checkItemService;

    @Override
    public UnitItemDetailedVO detailed(Long id) throws ValidationException {
        UnitItemPO po = mapper.selectById(id);
        UnitItemDetailedVO detailedVO = BeanUtils.copyPOJO(po, UnitItemDetailedVO.class);

        // 填充条目详细
        CheckItemVO item = checkItemService.detailed(po.getItemId());
        detailedVO.setCheckItem(item);
        return detailedVO;
    }

    @Override
    public UnitItemDetailedVO create(UnitItemQuery query) throws ValidationException {
        // 该模块分数和加上新分数没有超过100
        if (query.getMark() + this.toFraction(query.getUnitId()) > 100)
            throw new ValidationException("一个模块的分数和不能超过100");

        UnitItemPO po = BeanUtils.copyPOJO(query, UnitItemPO.class);
        log.info(po);
        mapper.insert(po);
        return this.detailed(po.getId());
    }

    /**
     * 根据模块获取分数
     *
     * @param checkUnitId 模块编号
     * @return 该模块分数和
     */
    private Long toFraction(Long checkUnitId) {

        QueryWrapper<UnitItemPO> qw = new QueryWrapper<>();
        qw.eq("unit_id", checkUnitId);
        qw.select("IFNULL(SUM(mark), 0)");
        return Long.parseLong(String.valueOf(mapper.selectObjs(qw).get(0)));
    }
}